// Copyright (c) HashiCorp, Inc.
// SPDX-License-Identifier: MPL-2.0

package synapse

import (
	"fmt"
	"log"
	"time"

	"github.com/Azure/azure-sdk-for-go/services/preview/synapse/mgmt/v2.0/synapse" // nolint: staticcheck
	"github.com/hashicorp/go-azure-helpers/lang/pointer"
	"github.com/hashicorp/terraform-provider-azurerm/internal/clients"
	"github.com/hashicorp/terraform-provider-azurerm/internal/services/synapse/parse"
	"github.com/hashicorp/terraform-provider-azurerm/internal/services/synapse/validate"
	"github.com/hashicorp/terraform-provider-azurerm/internal/tf/pluginsdk"
	"github.com/hashicorp/terraform-provider-azurerm/internal/tf/validation"
	"github.com/hashicorp/terraform-provider-azurerm/internal/timeouts"
	"github.com/hashicorp/terraform-provider-azurerm/utils"
)

func resourceSynapseWorkspaceVulnerabilityAssessment() *pluginsdk.Resource {
	return &pluginsdk.Resource{
		Create: resourceSynapseWorkspaceVulnerabilityAssessmentCreateUpdate,
		Read:   resourceSynapseWorkspaceVulnerabilityAssessmentRead,
		Update: resourceSynapseWorkspaceVulnerabilityAssessmentCreateUpdate,
		Delete: resourceSynapseWorkspaceVulnerabilityAssessmentDelete,

		Timeouts: &pluginsdk.ResourceTimeout{
			Create: pluginsdk.DefaultTimeout(30 * time.Minute),
			Read:   pluginsdk.DefaultTimeout(5 * time.Minute),
			Update: pluginsdk.DefaultTimeout(30 * time.Minute),
			Delete: pluginsdk.DefaultTimeout(30 * time.Minute),
		},

		Importer: pluginsdk.ImporterValidatingResourceId(func(id string) error {
			_, err := parse.WorkspaceVulnerabilityAssessmentID(id)
			return err
		}),

		Schema: map[string]*pluginsdk.Schema{
			"workspace_security_alert_policy_id": {
				Type:         pluginsdk.TypeString,
				Required:     true,
				ForceNew:     true,
				ValidateFunc: validate.WorkspaceSecurityAlertPolicyID,
			},

			"storage_container_path": {
				Type:         pluginsdk.TypeString,
				Required:     true,
				ValidateFunc: validation.StringIsNotEmpty,
			},

			"recurring_scans": {
				Type:     pluginsdk.TypeList,
				Optional: true,
				// NOTE: O+C API returns defaults for these even if omitted so this needs to remain
				Computed: true,
				MaxItems: 1,
				Elem: &pluginsdk.Resource{
					Schema: map[string]*pluginsdk.Schema{
						"email_subscription_admins_enabled": {
							Type:     pluginsdk.TypeBool,
							Optional: true,
							Default:  true,
						},

						"emails": {
							Type:     pluginsdk.TypeList,
							Optional: true,
							Elem: &pluginsdk.Schema{
								Type:         pluginsdk.TypeString,
								ValidateFunc: validation.StringIsNotEmpty,
							},
						},

						"enabled": {
							Type:     pluginsdk.TypeBool,
							Optional: true,
							Default:  false,
						},
					},
				},
			},

			"storage_account_access_key": {
				Type:         pluginsdk.TypeString,
				Optional:     true,
				Sensitive:    true,
				ValidateFunc: validation.StringIsNotEmpty,
			},

			"storage_container_sas_key": {
				Type:         pluginsdk.TypeString,
				Optional:     true,
				Sensitive:    true,
				ValidateFunc: validation.StringIsNotEmpty,
			},
		},
	}
}

func resourceSynapseWorkspaceVulnerabilityAssessmentCreateUpdate(d *pluginsdk.ResourceData, meta interface{}) error {
	client := meta.(*clients.Client).Synapse.WorkspaceVulnerabilityAssessmentsClient
	ctx, cancel := timeouts.ForCreateUpdate(meta.(*clients.Client).StopContext, d)
	defer cancel()

	policyId, err := parse.WorkspaceSecurityAlertPolicyID(d.Get("workspace_security_alert_policy_id").(string))
	if err != nil {
		return err
	}

	policyClient := meta.(*clients.Client).Synapse.WorkspaceSecurityAlertPolicyClient
	policy, err := policyClient.Get(ctx, policyId.ResourceGroup, policyId.WorkspaceName)
	if err != nil {
		return fmt.Errorf("retrieving %s: %+v", policyId, err)
	}

	id := parse.NewWorkspaceVulnerabilityAssessmentID(policyId.SubscriptionId, policyId.ResourceGroup, policyId.WorkspaceName, "default")

	if policy.State != synapse.SecurityAlertPolicyStateEnabled {
		return fmt.Errorf("updating %s: security alert policy is not enabled", id)
	}

	vulnerabilityAssessment := expandServerVulnerabilityAssessment(d)

	_, err = client.CreateOrUpdate(ctx, policyId.ResourceGroup, policyId.WorkspaceName, *vulnerabilityAssessment)
	if err != nil {
		return fmt.Errorf("updating %s: %+v", id, err)
	}

	d.SetId(id.ID())

	return resourceSynapseWorkspaceVulnerabilityAssessmentRead(d, meta)
}

func resourceSynapseWorkspaceVulnerabilityAssessmentRead(d *pluginsdk.ResourceData, meta interface{}) error {
	client := meta.(*clients.Client).Synapse.WorkspaceVulnerabilityAssessmentsClient
	ctx, cancel := timeouts.ForRead(meta.(*clients.Client).StopContext, d)
	defer cancel()

	id, err := parse.WorkspaceVulnerabilityAssessmentID(d.Id())
	if err != nil {
		return err
	}

	resp, err := client.Get(ctx, id.ResourceGroup, id.WorkspaceName)
	if err != nil {
		if utils.ResponseWasNotFound(resp.Response) {
			log.Printf("[INFO] synapse %s does not exist - removing from state", id)
			d.SetId("")
			return nil
		}

		return fmt.Errorf("retrieving %s: %+v", id, err)
	}

	policyClient := meta.(*clients.Client).Synapse.WorkspaceSecurityAlertPolicyClient
	policy, err := policyClient.Get(ctx, id.ResourceGroup, id.WorkspaceName)
	if err != nil {
		return fmt.Errorf("retrieving security alert policy for %s: %+v", id, err)
	}
	d.Set("workspace_security_alert_policy_id", policy.ID)

	if props := resp.ServerVulnerabilityAssessmentProperties; props != nil {
		d.Set("storage_container_path", props.StorageContainerPath)

		if v, ok := d.GetOk("storage_account_access_key"); ok {
			d.Set("storage_account_access_key", v)
		}

		if v, ok := d.GetOk("storage_container_sas_key"); ok {
			d.Set("storage_container_sas_key", v)
		}

		if props.RecurringScans != nil {
			d.Set("recurring_scans", flattenRecurringScans(props.RecurringScans))
		}
	}
	return nil
}

func resourceSynapseWorkspaceVulnerabilityAssessmentDelete(d *pluginsdk.ResourceData, meta interface{}) error {
	client := meta.(*clients.Client).Synapse.WorkspaceVulnerabilityAssessmentsClient
	ctx, cancel := timeouts.ForDelete(meta.(*clients.Client).StopContext, d)
	defer cancel()

	id, err := parse.WorkspaceVulnerabilityAssessmentID(d.Id())
	if err != nil {
		return err
	}

	if _, err = client.Delete(ctx, id.ResourceGroup, id.WorkspaceName); err != nil {
		return fmt.Errorf("deleting %s: %+v", id, err)
	}

	return nil
}

func expandServerVulnerabilityAssessment(d *pluginsdk.ResourceData) *synapse.ServerVulnerabilityAssessment {
	storageContainerPath := d.Get("storage_container_path").(string)

	vulnerabilityAssessment := synapse.ServerVulnerabilityAssessment{
		ServerVulnerabilityAssessmentProperties: &synapse.ServerVulnerabilityAssessmentProperties{
			StorageContainerPath: &storageContainerPath,
		},
	}

	props := vulnerabilityAssessment.ServerVulnerabilityAssessmentProperties

	if v, ok := d.GetOk("storage_account_access_key"); ok {
		props.StorageAccountAccessKey = pointer.To(v.(string))
	}

	if v, ok := d.GetOk("storage_container_sas_key"); ok {
		props.StorageContainerSasKey = pointer.To(v.(string))
	}

	if _, ok := d.GetOk("recurring_scans"); ok {
		props.RecurringScans = expandRecurringScans(d)
	}

	return &vulnerabilityAssessment
}

func expandRecurringScans(d *pluginsdk.ResourceData) *synapse.VulnerabilityAssessmentRecurringScansProperties {
	props := synapse.VulnerabilityAssessmentRecurringScansProperties{}

	vs := d.Get("recurring_scans").([]interface{})
	if len(vs) == 0 {
		return &props
	}

	v := vs[0].(map[string]interface{})

	if enabled, ok := v["enabled"]; ok {
		props.IsEnabled = pointer.To(enabled.(bool))
	}

	if emailSubscriptionAdmins, ok := v["email_subscription_admins_enabled"]; ok {
		props.EmailSubscriptionAdmins = pointer.To(emailSubscriptionAdmins.(bool))
	}

	if _, ok := v["emails"]; ok {
		emails := make([]string, 0)
		for _, uri := range v["emails"].([]interface{}) {
			emails = append(emails, uri.(string))
		}
		props.Emails = &emails
	}

	return &props
}

func flattenRecurringScans(props *synapse.VulnerabilityAssessmentRecurringScansProperties) []interface{} {
	result := make(map[string]interface{})

	if enabled := props.IsEnabled; enabled != nil {
		result["enabled"] = *props.IsEnabled
	}

	if emailSubscriptionAdmins := props.EmailSubscriptionAdmins; emailSubscriptionAdmins != nil {
		result["email_subscription_admins_enabled"] = *props.EmailSubscriptionAdmins
	}

	if props.Emails != nil {
		result["emails"] = *props.Emails
	}

	return []interface{}{result}
}
